from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import User


# Create your models here.


# 帖子模式
class Post(models.Model):
    user = models.ForeignKey('user.User', on_delete=models.CASCADE, verbose_name='用户')
    title = models.CharField(max_length=200, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    like_count = models.IntegerField(default=0, verbose_name='点赞数')
    comment_count = models.IntegerField(default=0, verbose_name='评论数')
    share_count = models.IntegerField(default=0, verbose_name='分享数')
    star_count = models.IntegerField(default=0, verbose_name='收藏数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    category = models.CharField(max_length=50, verbose_name='分类', default='其他')
    image = models.ImageField(upload_to='posts/images/', null=True, blank=True, verbose_name='配图')
    source = models.CharField(max_length=50, verbose_name='来源', default='', blank=True)
    tags = models.CharField(max_length=200, verbose_name='标签', default='', blank=True)

    class Meta:
        db_table = 'post'
        verbose_name = '帖子'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']  # 按照发布时间排序

    def __str__(self):
        return self.title


# 喜欢
class PostLike(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('post', 'user')  # 保证同一用户对同一帖子只能点赞一次


# 收藏
class PostStar(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('post', 'user')  # 保证同一用户对同一帖子只能收藏一次


# 评论
class Comment(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments', verbose_name='所属帖子')
    user = models.ForeignKey('user.User', on_delete=models.CASCADE, verbose_name='评论用户')
    content = models.TextField(verbose_name='评论内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='评论时间')
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='replies',
                               verbose_name='父评论')

    class Meta:
        ordering = ['created_at']
        verbose_name = '评论'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.user}：{self.content[:20]}"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # 只有顶级评论才更新帖子评论总数
        if self.parent is None:
            self.post.comment_count = Comment.objects.filter(post=self.post, parent=None).count()
            self.post.save(update_fields=['comment_count'])


# 使用信号，在删除评论后更新评论数
@receiver(post_delete, sender=Comment)
def update_comment_count_on_delete(sender, instance, **kwargs):
    # 只有顶级评论的删除才更新帖子评论总数
    if instance.parent is None:
        post = instance.post
        post.comment_count = Comment.objects.filter(post=post, parent=None).count()
        post.save(update_fields=['comment_count'])
